#!/bin/bash

# 启动多个ChunkServer进程脚本 (支持EC 4+2模式)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== 启动多个ChunkServer进程 ===${NC}"

# 获取脚本所在目录
SCRIPT_DIR=$(cd $(dirname $0); pwd)
LOG_DIR="$SCRIPT_DIR/logs"

# 创建日志目录
mkdir -p "$LOG_DIR"

# 定义端口列表 (EC 4+2模式需要6个chunkserver)
PORTS=(50051 50052 50053 50054 50055 50056)

echo -e "${YELLOW}将启动 ${#PORTS[@]} 个ChunkServer进程:${NC}"
for port in "${PORTS[@]}"; do
    echo "  - 端口 $port"
done
echo ""

# 检查是否已有chunkserver在运行
RUNNING_PORTS=()
for port in "${PORTS[@]}"; do
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        RUNNING_PORTS+=($port)
    fi
done

if [ ${#RUNNING_PORTS[@]} -gt 0 ]; then
    echo -e "${YELLOW}警告: 以下端口已被占用:${NC}"
    for port in "${RUNNING_PORTS[@]}"; do
        echo "  - 端口 $port"
    done
    echo ""
    read -p "是否继续启动其他端口的ChunkServer? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}操作已取消${NC}"
        exit 0
    fi
fi

# 启动chunkserver进程
SUCCESS_COUNT=0
FAILED_PORTS=()

for port in "${PORTS[@]}"; do
    # 检查端口是否被占用
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo -e "${YELLOW}跳过端口 $port (已被占用)${NC}"
        FAILED_PORTS+=($port)
        continue
    fi
    
    echo -e "${BLUE}启动ChunkServer (端口: $port)...${NC}"
    
    # 启动chunkserver
    cd "$SCRIPT_DIR/persistent_layer/chunkserver/build"
    nohup yes | ./chunkserver_server --port $port > "$LOG_DIR/chunkserver_$port.log" 2>&1 &
    CHUNKSERVER_PID=$!
    
    # 等待一下让进程启动
    sleep 1
    
    # 检查进程是否成功启动
    if kill -0 $CHUNKSERVER_PID 2>/dev/null; then
        echo -e "${GREEN}✓ ChunkServer (端口: $port) 启动成功${NC}"
        echo "  进程ID: $CHUNKSERVER_PID"
        
        # 保存PID到文件
        echo $CHUNKSERVER_PID > "$LOG_DIR/chunkserver_$port.pid"
        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
    else
        echo -e "${RED}✗ ChunkServer (端口: $port) 启动失败${NC}"
        FAILED_PORTS+=($port)
    fi
done

echo ""
echo -e "${BLUE}=== 启动结果 ===${NC}"
echo -e "${GREEN}成功启动: $SUCCESS_COUNT 个ChunkServer${NC}"

if [ ${#FAILED_PORTS[@]} -gt 0 ]; then
    echo -e "${RED}启动失败: ${#FAILED_PORTS[@]} 个端口${NC}"
    for port in "${FAILED_PORTS[@]}"; do
        echo "  - 端口 $port"
    done
fi

echo ""
echo -e "${YELLOW}查看所有日志:${NC}"
for port in "${PORTS[@]}"; do
    if [ -f "$LOG_DIR/chunkserver_$port.log" ]; then
        echo "  tail -f $LOG_DIR/chunkserver_$port.log"
    fi
done

echo ""
echo -e "${YELLOW}停止所有ChunkServer:${NC}"
echo "  ./stop_multiple_chunkservers.sh"
echo ""
echo -e "${YELLOW}停止单个ChunkServer:${NC}"
echo "  ./stop_chunkserver.sh [端口号]"
echo ""
echo -e "${GREEN}多ChunkServer启动完成！${NC}" 